package com.jaj.services.rap;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jaj.common.HttpUtils;
import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.MethodDoc;
import com.sun.javadoc.ParamTag;
import com.sun.javadoc.Tag;
import org.apache.http.Header;
import org.apache.http.client.utils.DateUtils;
import org.apache.http.message.BasicHeader;

/**
 * Created by chm on 2018/1/24.
 *
 * @author j aj
 */
public class ProjectService {

    /**
     * 删除Project
     * @param sessionId 用户Sessionid
     * @param projectId 项目Id
     * @return 是否成功
     */
    public static boolean deleteProject(String sessionId,String projectId){
        String url=RapConfig.Url.Project.Delete;
        //拼装参数
        Map<String, String> param = new HashMap<>();
        param.put("id", projectId);
        //拼接Cookie（包含登录信息）
        List<Header> headerList = new ArrayList<>();
        Header header = new BasicHeader("Cookie", "JSESSIONID=" + sessionId);
        headerList.add(header);
        try {
            String httpReturn = HttpUtils.httpClientPost(url, param, headerList);
            JSONObject jsonObject = JSON.parseObject(httpReturn);
            if (jsonObject.getInteger("code") == 200) {
                return true;
            }
            return false;
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 创建Project
     *
     * @param sessionId 用户SessionId
     * @param groupId 分组Id
     * @param name 名称
     * @param accounts 用户群
     * @param desc 描述
     * @return 结果
     */
    public static String createProject(String sessionId, String groupId, String name, String accounts, String desc) {
        String url = RapConfig.Url.Project.Create;
        //拼装参数
        Map<String, String> param = new HashMap<>();
        param.put("groupId", groupId);
        param.put("name", name);
        param.put("accounts", accounts);
        param.put("desc", desc);
        //拼接Cookie（包含登录信息）
        List<Header> headerList = new ArrayList<>();
        Header header = new BasicHeader("Cookie", "JSESSIONID=" + sessionId);
        headerList.add(header);
        try {
            String httpReturn = HttpUtils.httpClientPost(url, param, headerList);
            JSONObject jsonObject = JSON.parseObject(httpReturn);
            if (jsonObject.getInteger("code") == 200) {
                JSONObject result = jsonObject.getJSONObject("result");
                return result.getString("id");
            }
            return null;
        }
        catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    /**
     * 锁定项目
     *
     * @param sessionId 用户session
     * @param projectId Project的Id
     */
    public static boolean lockProject(String sessionId, String projectId) {
        String url = RapConfig.Url.Project.Lock;
        //拼装参数
        Map<String, String> param = new HashMap<String, String>();
        param.put("id", projectId);
        //拼接Cookie（包含登录信息）
        List<Header> headerList = new ArrayList<Header>();

        Header header = new BasicHeader("Cookie", "JSESSIONID=" + sessionId);
        headerList.add(header);
        try {
            String httpReturn = HttpUtils.httpClientPost(url, param, headerList);
            JSONObject jsonObject = JSON.parseObject(httpReturn);
            return jsonObject.getBoolean("isOk");
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 解锁项目
     *
     * @param sessionId 用户session
     * @param projectId Project的Id
     */
    public static boolean unLockProject(String sessionId, String projectId) {
        String url = RapConfig.Url.Project.UnLock;
        //拼装参数
        Map<String, String> param = new HashMap<>();
        param.put("id", projectId);
        //拼接Cookie（包含登录信息）
        List<Header> headerList = new ArrayList<>();

        Header header = new BasicHeader("Cookie", "JSESSIONID=" + sessionId);
        headerList.add(header);
        try {
            String httpReturn = HttpUtils.httpClientPost(url, param, headerList);
            JSONObject jsonObject = JSON.parseObject(httpReturn);
            if (jsonObject.getInteger("code") == 200) {
                return true;
            }
            else {
                return false;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 创建入参
     *
     * @param tagList JavaDoc中的Tags列表
     * @return
     */
    public static JSONArray createRequestParameterList(List<Tag> tagList) {
        JSONArray jsonArray = new JSONArray();
        if (tagList != null && tagList.size() > 0) {
            for (Tag tag : tagList) {
                if (tag instanceof ParamTag) {
                    ParamTag paramTag = (ParamTag) tag;
                    JSONObject jb = new JSONObject();
                    jb.put("identifier", paramTag.parameterName());
                    jb.put("name", paramTag.parameterComment());
                    jb.put("remark", "");
                    jb.put("validator", "");
                    jb.put("dataType", "string");
                    jb.put("parameterList", new JSONArray());
                    jsonArray.add(jb);
                }
            }
        }
        return jsonArray;
    }

    /**
     * 创建返回参数
     *
     * @param tagList JavaDoc中的Tags列表
     * @return
     */
    public static JSONArray createResponseParameterList(List<Tag> tagList) {
        JSONArray jsonArray = new JSONArray();
        if (tagList != null && tagList.size() > 0) {
            for (Tag tag : tagList) {
                if (tag.name().equals("@return")) {
                    JSONObject jb = new JSONObject();
                    jb.put("identifier", "");
                    jb.put("name", "");
                    jb.put("remark", tag.text());
                    jb.put("validator", "");
                    jb.put("dataType", "string");
                    jb.put("parameterList", new JSONArray());
                    jsonArray.add(jb);
                }
            }
        }
        return jsonArray;
    }

    /**
     * 创建方法Action
     *
     * @param methodDocList
     * @return
     */
    public static JSONArray createActionList(List<MethodDoc> methodDocList) {
        JSONArray jsonArray = new JSONArray();
        int i=0;
        if (methodDocList != null && methodDocList.size() > 0) {
            for (MethodDoc methodDoc : methodDocList) {
                JSONObject jb = new JSONObject();
                jb.put("requestParameterList", createRequestParameterList(Arrays.asList(methodDoc.tags())));
                jb.put("responseParameterList", createResponseParameterList(Arrays.asList(methodDoc.tags())));
                i++;
                String no=String.valueOf(i);
                if(i<10){
                    no="0"+no;
                }
                jb.put("name", no+"--"+methodDoc.commentText() + "(" + methodDoc.name() + ")");
                jb.put("description", methodDoc.commentText() + "  " + methodDoc.name());
                jb.put("requestType", "1");
                jb.put("requestUrl", methodDoc.qualifiedName());
                jb.put("responseTemplate", "");
                jsonArray.add(jb);
            }
        }
        return jsonArray;
    }

    /**
     * 创建Page
     *
     * @param classDoc
     * @return
     */
    public static JSONArray createPageList(ClassDoc classDoc) {
        JSONArray jsonArray = new JSONArray();
        if (classDoc != null) {
            JSONObject jb = new JSONObject();
            jb.put("actionList", createActionList(Arrays.asList(classDoc.methods())));
            jb.put("name", classDoc.commentText());
            jb.put("introduction", classDoc.qualifiedName());
            jsonArray.add(jb);
        }
        return jsonArray;
    }

    /**
     * 创建Module
     *
     * @param classDoc
     * @return
     */
    public static JSONArray createModuleList(ClassDoc classDoc) {
        JSONArray jsonArray = new JSONArray();
        if (classDoc != null) {
            JSONObject jb = new JSONObject();
            jb.put("pageList", createPageList(classDoc));
            jb.put("name", classDoc.commentText());
            jb.put("introduction", classDoc.qualifiedName());
            jsonArray.add(jb);
        }
        return jsonArray;
    }

    public static JSONObject createProjectData(ClassDoc classDoc) {
        JSONObject jb = new JSONObject();
        jb.put("moduleList", createModuleList(classDoc));
        jb.put("name", classDoc.commentText());
        jb.put("introduction", classDoc.qualifiedName() + "  " + classDoc.commentText());
        jb.put("version", "0.0.0.1");
        jb.put("createDateStr", DateUtils.formatDate(new Date(), "yyyy-MM-dd"));
        JSONObject user = new JSONObject();
        user.put("id", "21");
        user.put("name", "焦安健");
        jb.put("user", user);
        return jb;
    }

    public static boolean checkIn(String sessionId, ClassDoc classDoc, String projectId) {
        String url = RapConfig.Url.Project.CheckIn;
        //拼装参数
        Map<String, String> param = new HashMap<>();
        param.put("id", projectId);
        param.put("projectData", createProjectData(classDoc).toJSONString());
        param.put("deletedObjectListData", new JSONArray().toJSONString());
        param.put("versionPosition", "1");
        param.put("description", "quick save");
        //拼接Cookie（包含登录信息）
        List<Header> headerList = new ArrayList<>();
        Header header = new BasicHeader("Cookie", "JSESSIONID=" + sessionId);
        headerList.add(header);
        String httpReturn="";
        try {
            httpReturn = HttpUtils.httpClientPost(url, param, headerList);
            JSONObject jsonObject = JSON.parseObject(httpReturn);
            if (jsonObject.getBoolean("isOk")) {
                return true;
            }
            return false;
        }
        catch (Exception e) {
            System.err.println(JSON.toJSONString(param));
            System.err.println(httpReturn);
            e.printStackTrace();
            return false;
        }
    }



    public static void main(String[] args) {
        //1创建Project
        String sessionId = LoginService.rapLogin("", "");
//        String projectId= ProjectService.createProject(sessionId,RapConfig.Group.FeedbackSystem,"测试一123","jiaoanjian(焦安健),chenlingfei(陈领飞)","描述测试");
//        System.err.println(projectId);
        //2锁定Project
//       boolean isLock= lockProject(sessionId,"2063");
//        System.err.println(isLock);
        //3解锁Project
//        boolean isUnLock = unLockProject(sessionId, "2063");
//        System.err.println(isUnLock);
        //4删除Project
        boolean isDelete=deleteProject(sessionId,"2075");
    }

}
